<template>
  <div style="padding: 10px">
    <div class="all-xmu w">
      <div class="xmu-l l">
        <!--  搜素结果页 -->
        <div class="l-jieguo">
          <!-- 搜索项目区 -->
          <ul class="jieguo-jieguo">
            <div style="border-bottom: 1px dashed #e2e5e6" class="jieguo-xm" v-if="tableData.length!==0"
                 v-for="item in tableData" :key="item.orderNo">
              <div @click="$router.push('/front/orderDetail?id=' + item.id)"
                   style="cursor: pointer" class="cc-title">
                <img v-if="item.status===1" class="l cc-haibao" :src="item.ticket.concert.coverImg"
                     alt="项目海报">
                <img v-else class="l cc-haibao" style="opacity: 50%" :src="item.ticket.concert.coverImg"
                     alt="项目海报">
              </div>
              <div class="xm-l l">
                <a v-if="item.status===1"
                   @click="$router.push('/front/orderDetail?id=' + item.id)" class="cc-title"
                   target="_blank">
                  {{ item.ticket.concert.name }} </a>
                <a v-else @click="$router.push('/front/orderDetail?id=' + item.id)"
                   style="color: #9b9b9b" target="_blank">
                  {{ item.ticket.concert.name }} </a>
                <span class="blc cc-changguan">
									&nbsp;订单编号：{{ item.orderNo }}
								</span>
                <span class="blc cc-time">&nbsp;下单时间：{{ item.orderTime }}</span>
                <span class="blc cc-changguan">&nbsp;地址：[{{
                    item.ticket.concert.venue.address
                  }}]{{ item.ticket.concert.venue.name }}</span>
                <span>&nbsp;数量：{{ item.ticketTotal }}&nbsp;张</span>
                <span v-if="item.status===1" style="position:relative;bottom: 156px;left: 400px"
                      class="countdown-timer">订单倒计时: {{ formatOrderCountdown(item.remainingTime) }}</span>
              </div>
              <div class="xm-r r">
								<span class="r-jiage">总计
									<span v-if="item.status===1" style="color: #f64d24"
                        class="cc-price">{{ item.totalPrice }}</span>
									<span v-else class="cc-price" style="color: #7c7c7c">{{ item.totalPrice }}
									</span>
								</span>
                <div
                    style="position: relative;top: 25px;right: 5px; display: flex;width: 150px;flex-direction: row;justify-content: space-between">
                  <a @click="pay(item)" v-if="item.status===1"
                     style="position: relative;right: 50px" class="blc" target="_blank">立即支付</a>
                  <a v-else style="position: relative;right: 50px" class="blc" target="_blank"
                     @click="$router.push('/front/ticketDetail?id=' + item.ticket.concert.id)">再来一单</a>
                  <a v-if="item.status===1" class="blc"
                     style="background-color: white;color: #9b9b9b;position: relative;right: 30px"
                     target="_blank" @click="dialogVisible = true;form=item;">取消订单</a>
                  <a v-if="item.status===2" class="blc"
                     style="background-color: white;color: #9b9b9b;position: relative;right: 30px"
                     target="_blank">已支付</a>
                  <a v-if="item.status===3" class="blc"
                     style="background-color: white;color: #9b9b9b;position: relative;right: 30px"
                     target="_blank">已取消</a>
                </div>
              </div>
            </div>
            <div v-if="tableData.length===0">暂无订单</div>
          </ul>
          <div class="M-box1"></div>
        </div>
      </div>
      <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
        <span>您确定要取消订单吗？</span>
        <span slot="footer" class="dialog-footer">
					<el-button @click="dialogVisible = false">我点错了</el-button>
					<el-button type="primary" @click="cancelOrder();dialogVisible=false">确 定</el-button>
				</span>
      </el-dialog>
    </div>
    <div style="padding: 10px 0">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                     :page-sizes="[2, 5, 10, 20]" :page-size="pageSize" layout="total, prev, pager, next" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>
export default {
  name: "Order",
  data() {
    return {
      pageNum: 1,
      pageSize: 5,
      total: 6,
      tableData: [],
      orderNo: '',
      dialogVisible: false,
      form: {},
      timers: {}
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.request.get("/user/order/front/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderNo: this.orderNo,
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
        console.log(this.tableData)
        // 初始化倒计时
        this.initCountdowns();
      })
    },
    pay(item) {
      window.open("http://localhost:9090/order/pay?subject=" +
          item.ticket.concert.name + "&traceNo=" + item.orderNo +
          "&totalAmount=" + item.totalPrice)
    },
    cancelOrder() {
      let form = {
        id: this.form.id,
        totalPrice: this.form.totalPrice,
        status: 3
      };
      this.request.post("/user/order", form).then(res => {
        if (res.code === 200) {
          this.$message.success("订单取消成功")
          this.load()
        } else {
          this.$message.error("订单取消失败")
        }
      })
    },
    // 初始化所有订单的倒计时
    initCountdowns() {
      // 先清除现有的所有定时器
      this.clearAllTimers();

      this.tableData.forEach(item => {
        if (item.status === 1 && item.remainingTime > 0) {
          this.startOrderCountdown(item);
        }
      });
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.load()
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.load()
    },
    // 为单个订单启动倒计时
    startOrderCountdown(order) {
      // 如果已经存在该订单的定时器，则先清除
      if (this.timers[order.orderNo]) {
        clearInterval(this.timers[order.orderNo]);
      }

      // 设置新的定时器
      this.timers[order.orderNo] = setInterval(() => {
        if (order.remainingTime > 0) {
          order.remainingTime--;
        } else {
          // 订单超时，清除定时器并更新订单状态
          clearInterval(this.timers[order.orderNo]);
          delete this.timers[order.orderNo];
          // 使用 Vue.set 或 this.$set 确保视图更新
          // this.$set(order, 'status', 3);
          // 也可以用这种方式更新状态
          order.status = 3;
          this.load()
        }
      }, 1000);
    },
    // 格式化单个订单的倒计时显示
    formatOrderCountdown(remainingTime) {
      const minutes = Math.floor(remainingTime / 60);
      const seconds = remainingTime % 60;
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    },
    // 清除所有定时器
    clearAllTimers() {
      Object.values(this.timers).forEach(timer => clearInterval(timer));
      this.timers = {};
    }
  },
  beforeDestroy() {
    // 组件销毁前清除所有定时器
    this.clearAllTimers();
  },
}
</script>

<style src="../../static/css/common.css" scoped></style>
<style src="../../static/css/allitems.css" scoped></style>
<style scoped>
.countdown-timer {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}
</style>
